// pages/post-detail/post-detail.js
import {
  postList
} from '../../data/data.js'

const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    postData: {},
    collected: false,
    isPlaying: false,
    _pid: null,
    _postCollected: {},
    _mgr: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const postData = postList[options.pid]
    this.data._pid = options.pid
    const postCollected = wx.getStorageSync('posts_collected')
    this.data._postCollected = postCollected == '' ? {} : postCollected
    let collected = postCollected[this.data._pid]
    if (collected === undefined) {
      collected = false;
    }
    this.setData({
      postData,
      collected,
      isPlaying:this.currentPostMusicIsPlaying()
    })

    const mgr = wx.getBackgroundAudioManager();
    this.data._mgr = mgr;
    mgr.onPlay(this.onMusicStart)
    mgr.onPause(this.onMusicStop)
  },
  currentPostMusicIsPlaying(){
    if(app.gIsPlayingMusic && app.gPostIdMusic === this.data._pid){
         return true;
    }else{
      return false;
    }
  },
  /**
   * 收藏文章
   */
  onCollect(event) {
    //从缓存中取出
    const postsColleted = this.data._postCollected
    postsColleted[this.data._pid] = !this.data.collected
    wx.setStorageSync('posts_collected', postsColleted)
    wx.showToast({
      title: !this.data.collected ? "收藏成功" : "取消收藏",
      duration: 1000
    })
    this.setData({
      collected: !this.data.collected
    })

  },
  onShare(event) {
    wx.showActionSheet({
      itemList: ['分享到QQ', '分享的微信'],
    })

  },
  //播放音乐
  onMusicStart(e) {
    const mgr = this.data._mgr;
    const music = postList[this.data._pid].music
    mgr.src = music.url
    mgr.title = music.title
    mgr.coverImgUrl = music.coverImg
    app.gIsPlayingMusic=true
    app.gPostIdMusic=this.data._pid
    this.setData({
      isPlaying: true
    })
  },

  onMusicStop(e) {
    const mgr = this.data._mgr;
    app.gIsPlayingMusic=false
    app.gPostIdMusic=-1
    mgr.stop()
    this.setData({
      isPlaying: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})